package com.gitee.minimalismstyle.fresh.common.web.util

import java.io.File
import java.net.URLEncoder
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

object WebUtils{

    fun download(request: HttpServletRequest, response: HttpServletResponse, path: String, name: String) {
        val filePath = WebUtils::class.java.getResource(path).path
        val file = File(filePath)
        download(request, response, file, name)
    }

    fun download(request: HttpServletRequest, response: HttpServletResponse, file: File, name: String) {
        download(request, response, file.readBytes(), name)
    }

    fun download(request: HttpServletRequest, response: HttpServletResponse, bt: ByteArray, name: String) {
        response.outputStream.use { os ->
            response.characterEncoding = "utf-8"
            response.contentType = "application/octet-stream;charset=UTF-8"
            response.setContentLength(bt.size)
            val encodedFileName = URLEncoder.encode(name, "UTF8")
            var contentDisposition = String.format("attachment;fileName=\"%s\"", encodedFileName)
            var userAgent = request.getHeader("User-Agent")
            if (userAgent != null) {
                userAgent = userAgent.toLowerCase()
                if (userAgent.indexOf("firefox") != -1) {
                    contentDisposition = String.format("attachment;fileName*=UTF-8''%s", encodedFileName)
                }
            }
            response.setHeader("Content-Disposition", contentDisposition)
            os.write(bt)
            os.flush()
        }
    }
}
